package com.fin.zw.aiqas.service;

import com.fin.zw.aiqas.entity.Department;
import com.fin.zw.aiqas.entity.QDepartment;
import com.fin.zw.aiqas.entity.QUserInfo;
import com.fin.zw.aiqas.entity.UserInfo;
import com.fin.zw.aiqas.model.request.DepartmentRequest;
import com.fin.zw.aiqas.model.response.DepartmentResponse;
import com.fin.zw.aiqas.model.session.SessionModel;
import com.fin.zw.aiqas.repository.DepartmentRepository;
import com.fin.zw.aiqas.repository.UserInfoRepository;
import com.fin.zw.aiqas.util.BadRequestException;
import com.fin.zw.aiqas.util.ShortUUID;
import com.google.common.collect.Lists;
import com.querydsl.core.BooleanBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service("departmentService")
public class DepartmentService {

    private final static Logger log = LoggerFactory.getLogger(DepartmentService.class);

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private UserInfoRepository userInfoRepository;


    /**
     * 查询所有的机构信息(树形机构)
     *
     * @param request
     * @return
     */
    public List<Department> getDepartment(DepartmentRequest request, SessionModel sessionModel) {
        BooleanBuilder builder = new BooleanBuilder();
        QDepartment qDepartment = QDepartment.department;
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        if (StringUtils.isNotEmpty(sessionModel.getDepartCode())) {
            builder.and(qDepartment.code.contains(sessionModel.getDepartCode()));
        }
        if (StringUtils.isNotEmpty(request.getName())) {
            builder.and(qDepartment.name.like("%".concat(request.getName().concat("%"))));
        }
        Iterator<Department> iterator = departmentRepository.findAll(builder, sort).iterator();
        List<Department> list = Lists.newArrayList(iterator);
        return list;
    }


    /**
     * 机构的添加
     *
     * @param request
     */
    public void createDepartment(DepartmentRequest request, SessionModel sessionModel) {
        Department department = new Department();
        BeanUtils.copyProperties(request, department);
        Iterator<Department> iterator = departmentRepository.findAll(QDepartment.department.name.eq(department.getName())).iterator();
        if(iterator.hasNext()){
            throw  new BadRequestException("", department.getName()+"部门已经存在!!!");
        }
        if (request.getParentId() != null) {
            Department parent = departmentRepository.findById(request.getParentId()).orElseThrow(() -> new BadRequestException("", "找不到对应的父机构信息"));
            department.setParent(parent);
            department.setCode(parent.getCode().concat("_").concat(ShortUUID.generateShortUuid()));
        } else {
            department.setCode(ShortUUID.generateShortUuid());
        }
        department.setCreateTime(new Date());
        department.setOperatorId(sessionModel.getUserId());
        department.setOperatorRealName(sessionModel.getUserName());
        departmentRepository.save(department);
    }


    /**
     * 机构的维护
     *
     * @param request
     */
    public void updateDepartment(DepartmentRequest request,SessionModel sessionModel) {
        Department department = departmentRepository.findById(request.getId()).orElseThrow(() -> new BadRequestException("", "需要修改得机构信息不存在"));
        if (request.getParentId() != null) {
            if (Objects.isNull(department.getParent()) || !department.getParent().getId().equals(request.getParentId())) {
                Department parent = departmentRepository.findById(request.getParentId()).orElseThrow(() -> new BadRequestException("", "找不到对应的父机构信息"));
                department.setParent(parent);
                department.setCode(department.getCode().concat("_").concat(ShortUUID.generateShortUuid()));
            }
        } else {
            department.setParent(null);
            department.setCode(ShortUUID.generateShortUuid());
        }
        department.setName(request.getName());
        department.setUpdateTime(new Date());
        department.setUpdateUserId(sessionModel.getUserId());
        department.setUpdateRealName(sessionModel.getUserName());
        departmentRepository.save(department);
    }

    /**
     * 机构的删除
     *
     * @param id
     */
    public void deleteDepartment(Long id) {
        Department department = departmentRepository.findById(id).orElseThrow(() -> new BadRequestException("", "选择的机构信息不存在！"));
        //暂时没有添加关联条件
        Iterator<UserInfo> infoIterator = userInfoRepository.findAll(QUserInfo.userInfo.department.code.contains(department.getCode())).iterator();
        if (infoIterator.hasNext()) {
            throw new BadRequestException("deletion not allowed", "该机构或其子机构存在用户信息，不允许删除！");
        }
        departmentRepository.delete(department);
    }

    /**
     * 获取机构列表信息
     * @return
     */
    public List<DepartmentResponse> getDepartmentAll() {
        Iterator<Department> iterator = departmentRepository.findAll().iterator();
        List<Department> list = Lists.newArrayList(iterator);
        List<DepartmentResponse> resultList = list.stream().map(department->{
            DepartmentResponse response = new DepartmentResponse();
            BeanUtils.copyProperties(department,response);
            if(Objects.nonNull(department.getParent())) {
                response.setParent(department.getParent().getId());
            }
            return response;
        }).collect(Collectors.toList());

        return resultList;
    }
}
